import { Component, OnInit, ViewChild } from '@angular/core';
import * as WebIM from '../../../../../src/webimSDK3.0.6.js'
import * as config from '../../../../../src/WebIMConfig.js'
import * as MessageUtlis from 'src/app/providers/MessageUtlis.js'
import { Storage } from 'src/app/providers/Storage.js';
import { IonContent } from '@ionic/angular';
import { Utils } from 'src/app/providers/Utils.js';
import { AuthService } from 'src/app/services/auth.service.js';
import { OrderService } from '../../../services/order.service';

@Component({
  selector: 'app-ttkefu',
  templateUrl: './ttkefu.page.html',
  styleUrls: ['./ttkefu.page.scss'],
})
export class TtkefuPage implements OnInit {
  listChat: any = [];
  list: any = [];
  sendMsg: string = '';
  imageName: string = '';
  connUtils: any = {};
  userId: string = 'hypekicker';
  phone: string = '';
  uid: string = '';
  imagePhoto: string = '../../../../assets/img/me/touxiang.png';
  @ViewChild(IonContent, null) content: IonContent;
  testRegister = '';
  loginIndex: number = 0;
  constructor(private authService:AuthService,private order:OrderService) {
  }
  ngOnInit() {




  
  

    
    



    
    Storage.sessionStorage.remove('isNewMsg');

    this.loginIndex = 0;

    let user = Storage.localStorage.get('userInfo');

 
    console.log("userBai",user)


    this.uid = user.userId;



    if(Storage.localStorage.get('thirdLogin')=="login"){
      this.phone = user.userPhone;
    }else if(Storage.localStorage.get('thirdLogin')=="google") {
      this.phone =  Storage.localStorage.get('GoogleEmail');
    }else{
      this.phone = user.userNickName;
    }
  
   
  
    let facebookAvatarUrl = '';
    
    console.log('user', user.userId);
    console.log('phone', this.phone);
    this.imagePhoto=this.order.getImageUrl()+user.avatarUrl;
    // if
    this.connUtils = MessageUtlis.MessageUtlis.getConn();
    if ( Storage.localStorage.get('listChat')) {
      this.list = Storage.localStorage.get('listChat');
      setTimeout(res => {
        this.content.scrollToBottom(0);
      }, 100)
    }
    this.registerUser(this.connUtils);
    console.log('更新了数据', this.list);
    // if (this.list.length>0) {
    //   this.open(this.connUtils);
    //   MessageUtlis.MessageUtlis.listen(this.connUtils,(callBack,type)=>{
    //     this.loginHX(callBack)
    //       this.list=Storage.localStorage.get('listChat');
    //       console.log('更新了数据',this.list);
    //       setTimeout(res=>{
    //           this.content.scrollToBottom(0);
    //         },100)
    //       });
    //   }else{
    //     this.registerUser(this.connUtils);
    //   }
    this.authService.getCustomerService({}).subscribe(res => {
      if (res.retCode == '000000') {
        this.userId=res.customerServiceId
      }
    })
  }

  focus() {
    setTimeout(() => {
      this.content.scrollToBottom(1);
    }, 1);
  }
  //登录
  open(conn) {
    if (this.loginIndex == 0) {
      this.loginIndex = this.loginIndex + 1;
      var options = {
        apiUrl: WebIM.config.apiURL,
        // user: this.uid,
        user: this.phone.replace('@', '') + this.testRegister,
        // pwd: this.phone,
        pwd: '123',
        appKey: WebIM.config.appkey,
        success: function (token) {
          // var token = token.access_token;
          // WebIM.utils.setCookie('webim_', token, 1);
          console.log('登录成功', token);
        },
        error: function () {
          // this.loginHX(false);
          console.log('登录失败');
        }
      };
      conn.open(options);
    }


  }
  errLogin() {
    this.loginHX(false);
  }
  undataList() {

  }
  loginHX(callBack) {
    if (!callBack) {
      this.open(this.connUtils);
      MessageUtlis.MessageUtlis.listen(this.connUtils, (callBack, type) => {
        // this.loginHX(callBack)
        this.loginIndex = 0;
        this.list = Storage.localStorage.get('listChat');
        console.log('更新了数据', this.list);
        setTimeout(res => {
          this.content.scrollToBottom(0);
        }, 100)
      });
    }
  }
  successData() {
    console.log('成功==');
    // setTimeout(res => {
    //   this.open(this.connUtils);
    //   MessageUtlis.MessageUtlis.listen(this.connUtils, (callBack, type) => {
    //     console.log('callBack=', callBack);
    //     this.loginIndex = 0;
    //     if (!callBack) {
    //       this.loginHX(callBack)
    //     }
    //     this.list = Storage.localStorage.get('listChat');
    //     console.log('更新了数据', this.list);
    //     setTimeout(res => {
    //       this.content.scrollToBottom(0);
    //     }, 100)
    //   });
    // }, 5000)

  }
  errorData() {
    console.log('注册失败了');
    let lmsg = Storage.localStorage.get('IS_MSG_LOGIN');
    let time = 0;
    if (!lmsg) {
      console.log('有延迟');
      time = 500;
      Storage.localStorage.set('IS_MSG_LOGIN', '1');
    }
    setTimeout(res => {
      this.open(this.connUtils);
      MessageUtlis.MessageUtlis.listen(this.connUtils, (callBack, type) => {
        console.log('callBack=', callBack);
        this.loginIndex = 0;
        if (!callBack) {
          this.loginHX(callBack)
        }
        this.list = Storage.localStorage.get('listChat');
        console.log('更新了数据', this.list);
        setTimeout(res => {
          this.content.scrollToBottom(0);
        }, 100)
      });
    }, time)

  }
  //注册
  registerUser(conn) {
    console.log('去注册');
    let nickName = '';
    let userInfo = Storage.localStorage.get('userInfo');
    // if (userInfo) {
    //   nickName=userInfo.userNickName
    // }else{
    //   nickName= this.phone
    // }
    var options = {
      username: this.phone.replace('@', '') + this.testRegister,
      password: '123',
      nickname: this.phone,
      appKey: WebIM.config.appkey,
      success: this.successData(),
      error: this.errorData(),
      // success: function (message) {
      //   console.log('message', message);
      // },
      apiUrl: WebIM.config.apiURL
    };
    console.log('conn', conn);

    conn.registerUser(options);
  }
  addMsg($event) {
  
    let input = document.getElementById('image');  // 选择图片的input
    let file = WebIM.default.utils.getFileUrl(input);      // 将图片转化为二进制文件
    let item = {
      id: '',
      from: this.userId,
      type: 'reply',
      typeMsg: 'img',
      nickName: this.phone,
      url: '',
      time: new Date().getTime(),
      sourceMsg: this.sendMsg,
      collectMsg: this.sendMsg,
    }
    if (!this.list) {
      this.list = [];
    }
    MessageUtlis.MessageUtlis.sendImgMSG(file, item, this.list, callBack => {
      this.imageName = ''
      this.list = Storage.localStorage.get('listChat');
      setTimeout(res => {
        this.content.scrollToBottom(0);
      }, 300)
      console.log('callBack==');
    })

  }


  onSend() {
    this.sendMsg = this.sendMsg.trim();
    let sMsg = this.sendMsg;
    this.sendMsg = ''
    if (sMsg) {
      let item = {
        id: '',
        from: this.userId,
        type: 'reply',
        nickName: this.phone,
        time: new Date().getTime(),
        sourceMsg: sMsg,
        collectMsg: sMsg,
      }
      if (!this.list) {
        this.list = [];
      } 
       
      MessageUtlis.MessageUtlis.sendMSG(sMsg, item, this.list, res => {
        if (Storage.localStorage.get('listChat')) {
          this.list = Storage.localStorage.get('listChat');
          setTimeout(res => {
            this.content.scrollToBottom(0);
          }, 100)
        }
      });
    }
  }


}
 